﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Net_SCADA;
using NetSCADA_QUERY;

namespace WZXC_GBL_QUERY
{
    public partial class Form_QueryDataByDay : Form
    {
        private Size ScreenSize;
        private bool isLoadInterface=false;
        private Dictionary<int,float[]> LineData=new Dictionary<int, float[]>();
        private Dictionary<int,CurveSetting> LineSetting=new Dictionary<int, CurveSetting>();
        Dictionary<CheckBox,List<CheckBox>> ZoneGroupChk=new Dictionary<CheckBox, List<CheckBox>>();
        Dictionary<CheckBox,List<Label>> ZoneGroupLbl=new Dictionary<CheckBox, List<Label>>();
        private Label TimeLine=new Label(){ Width=1,BackColor=Color.Black,Height=300,Location=new Point()};
        private Label TimeLabel=new Label(){ AutoSize=true,BackColor=Color.Transparent,ForeColor=Color.Green};
        private Label TimeData=new Label(){ AutoSize=true,BackColor=Color.Transparent,ForeColor=Color.Green};
        private float[,] limit=new float[2,5];
        private Label[] lbl_AxisLeft=new Label[6];
        private Label[] lbl_AxisRight=new Label[6];
        private List<Label> Equiplbl=new List<Label>();
        Ini inifile = new Ini(Application.StartupPath + @"\Settings\Curve.dat");
        private DateTime StartTime;
        private int SelectPanelCols=8;
        private int SelectPanelHeight=42;
        private int  SelectedGroupid;
        private int Xscale=1;
        private int CurveHeight=100;
        private int YAxisHeight=30;
        private DateTime lastQueryDate =DateTime.Now.AddDays(-10).Date;
        private int queryMinutes=1440;
        private int visiableminutes=0;

        private Dictionary<int, PVMaxMin> pvmaxmin=new Dictionary<int, PVMaxMin>();
        CheckBox leftAxisCheckbox = null;
        CheckBox rightAxisCheckbox = null;
        private Button selectedGroupButton=null;

        public Form_QueryDataByDay()
        {
            InitializeComponent();
        }

        private void Form_QueryDataByDay_Load(object sender , EventArgs e)
        {
            ScreenSize = Screen.PrimaryScreen.WorkingArea.Size;
            Show();
            SetInterface();
            LoadDayCurveSetting();
            LoadDayQueryButton();
            dtp_Day.Value = DateTime.Now.Date;
            QueryOneDayData(dtp_Day.Value);
        }
        private void SetInterface()
        {
            isLoadInterface = true;
            btn_Query.Location = new Point(ScreenSize.Width - btn_Query.Width - 2 , 1);
            btn_ShowAlarm.Location = new Point(ScreenSize.Width - btn_ShowAlarm.Width - 2 , 1);
            btn_DateAnalyze.Location =new Point( ScreenSize.Width - btn_ShowAlarm.Width - btn_DateAnalyze.Width - 10,1);

            gp_LoadData.Location = new Point((ScreenSize.Width - gp_LoadData.Width) / 2 , (ScreenSize.Height - gp_LoadData.Height) / 3);
            dtp_Day.Location = new Point(ScreenSize.Width - dtp_Day.Width - 65 , 1);
            dtp_Day.Value = DateTime.Now.Date;
            pnl_DayQuery.Location = new Point(0 , 33);
            pnl_DayQuery.Size = new Size(ScreenSize.Width , ScreenSize.Height - 60);
            pnl_Curve.Location = new Point(0 , 5);
            pnl_Curve.Size = new Size(ScreenSize.Width , pnl_DayQuery.Height - pnl_DayInfo.Height - pnl_Equip.Height - 5);
            pic_Curve.Location = new Point(pic_AxisL.Width , 0);
            visiableminutes = pnl_Curve.Width - pic_AxisL.Width - pic_AxisR.Width;
            pic_Curve.Height = pnl_Curve.Height;
            lbl_LeftTitle.Parent = pic_AxisL;
            lbl_RightTitle.Parent = pic_AxisR;
            lbl_RightTitle.Location = new Point(30 , 1);
            lbl_LeftTitle.Location = new Point(2 , 1);
            pic_Curve.Width = visiableminutes > queryMinutes ? visiableminutes : queryMinutes;
            for (int i = 0 ; i < lbl_AxisLeft.Length ; i++)
            {
                pic_AxisL.Controls.Add(lbl_AxisLeft[i] = new Label()
                {
                    Size = new Size(pic_AxisL.Width , 16) ,
                    TextAlign = ContentAlignment.TopRight
                });
                pic_AxisR.Controls.Add(lbl_AxisRight[i] = new Label()
                {
                    Size = new Size(pic_AxisR.Width , 16) ,
                    TextAlign = ContentAlignment.TopLeft
                });
            }
            for (int i = 0 ; i < 5 ; i++)
            {
                limit[0 , i] = Convert.ToInt32("0" + inifile.ReadValue("BoxCurve" + i , "Min"));
                limit[1 , i] = Convert.ToInt32("0" + inifile.ReadValue("BoxCurve" + i , "Max"));
            }
            Pnl_LimitSet.Location = new Point((ScreenSize.Width - Pnl_LimitSet.Width) / 2 , (ScreenSize.Height - Pnl_LimitSet.Height) / 2);
            isLoadInterface = false;
        }
        private void LoadDayQueryButton()
        {
            string[] groupid=DBOperate.GetZoneMonitorGroupUsed();
            if (groupid == null || groupid.Length <= 0) return;
            DataTable dtGroup=DBOperate.GetDesignGroupSet();
            if (dtGroup == null || dtGroup.Rows.Count <= 0) return;
            for (int i = groupid.Length - 1 ; i >= 0 ; i--)
            {
                Button btn=new Button()
                {
                    Size=new Size(150,50),
                    Text =dtGroup.Select("groupid=" + groupid[i])[0]["groupname"].ToString() ,
                    Font=new Font("微软雅黑",12f,FontStyle.Regular),
                    FlatStyle=FlatStyle.Flat,
                    Location=new Point(5+i*155,1),
                    Tag= groupid[i]
                };
                btn.Click += Btn_Click;
                pnl_Equip.Controls.Add(btn);
                if (i == 0) selectedGroupButton = btn;
            }
            if (int.TryParse(groupid[0] , out int id))
            {
                SelectedGroupid = id;
                ShowZoneSelections(id);
            }
        }

        private void ShowZoneSelections(int groupid)
        {
            int w=(pnl_DayInfo.Width -5* SelectPanelCols -5)/SelectPanelCols;
            pnl_DayInfo.Controls.Clear();
            ZoneGroupChk.Clear();
            ZoneGroupLbl.Clear();
            int totalzones=0;
            foreach (int i in QueryForms.fmquery.netline.zone.Keys)
            {
                if (QueryForms.fmquery.netline.zone[i].GroupID == groupid && QueryForms.fmquery.netline.zone[i].isShowCurve)
                {
                    Panel pnl =new Panel()
                    {
                        Size=new Size(w,SelectPanelHeight),
                        Location=new Point(5+(w+5)*(totalzones%SelectPanelCols),5+(SelectPanelHeight+5)*(totalzones/SelectPanelCols)),
                        BorderStyle=BorderStyle.FixedSingle,
                        BackColor=Color.LightYellow
                    };
                    CheckBox chk=new CheckBox()
                    {
                        Text= QueryForms.fmquery.netline.zone[i].ZoneName,
                        AutoSize=true,
                        Location=new Point(3,1),
                        Checked=GetZoneCurveSelection(QueryForms.fmquery.netline.zone[i].ID),
                        Tag= QueryForms.fmquery.netline.zone[i],
                    };
                    chk.CheckedChanged += EquipChk_CheckedChanged;
                    pnl.MouseDown += ZonePanel_MouseDown;
                    pnl.DoubleClick += ZonePanel_DoubleClick;
                    pnl.Controls.Add(chk);
                    ZoneGroupChk.Add(chk , new List<CheckBox>());
                    ZoneGroupLbl.Add(chk , new List<Label>());
                    if (QueryForms.fmquery.netline.zone[i].pv != null)
                    {
                        if (i == 0) leftAxisCheckbox = chk;
                        if (i == 1) rightAxisCheckbox = chk;
                        ZoneGroupChk[chk].Add(CreateCheckBox("pv" , new Size(w / 3 - SelectPanelHeight / 2 , SelectPanelHeight / 2) , new Point(SelectPanelHeight / 2 , SelectPanelHeight / 2) , QueryForms.fmquery.netline.zone[i].pv.ID , LineSetting[QueryForms.fmquery.netline.zone[i].pv.ID].isshow));
                        pnl.Controls.Add(ZoneGroupChk[chk].Last());
                        ZoneGroupLbl[chk].Add(CreateLabel(new Point(1 , SelectPanelHeight / 2 + 1) , LineSetting[QueryForms.fmquery.netline.zone[i].pv.ID].CurveColor , QueryForms.fmquery.netline.zone[i].pv.ID));
                        pnl.Controls.Add(ZoneGroupLbl[chk].Last());
                    }
                    if (QueryForms.fmquery.netline.zone[i].sv != null)
                    {
                        ZoneGroupChk[chk].Add(CreateCheckBox("sv" , new Size(w / 3 - SelectPanelHeight / 2 , SelectPanelHeight / 2) , new Point(w / 3 + SelectPanelHeight / 2 , SelectPanelHeight / 2) , QueryForms.fmquery.netline.zone[i].sv.ID , LineSetting[QueryForms.fmquery.netline.zone[i].sv.ID].isshow));
                        pnl.Controls.Add(ZoneGroupChk[chk].Last());
                        ZoneGroupLbl[chk].Add(CreateLabel(new Point(w / 3 + 1 , SelectPanelHeight / 2 + 1) , LineSetting[QueryForms.fmquery.netline.zone[i].sv.ID].CurveColor , QueryForms.fmquery.netline.zone[i].sv.ID));
                        pnl.Controls.Add(ZoneGroupLbl[chk].Last());
                    }
                    if (QueryForms.fmquery.netline.zone[i].ovpv != null)
                    {
                        ZoneGroupChk[chk].Add(CreateCheckBox("ovpv" , new Size(w / 3 - SelectPanelHeight / 2 , SelectPanelHeight / 2) , new Point(2 * w / 3 + SelectPanelHeight / 2 , SelectPanelHeight / 2) , QueryForms.fmquery.netline.zone[i].ovpv.ID , LineSetting[QueryForms.fmquery.netline.zone[i].ovpv.ID].isshow));
                        pnl.Controls.Add(ZoneGroupChk[chk].Last());
                        ZoneGroupLbl[chk].Add(CreateLabel(new Point(2 * w / 3 + 1 , SelectPanelHeight / 2 + 1) , LineSetting[QueryForms.fmquery.netline.zone[i].ovpv.ID].CurveColor , QueryForms.fmquery.netline.zone[i].ovpv.ID));
                        pnl.Controls.Add(ZoneGroupLbl[chk].Last());
                    }
                    pnl.Tag = chk;
                    pnl_DayInfo.Controls.Add(pnl);
                    totalzones++;
                }
            }
            showCurveByDay();
        }
        private void ZonePanel_MouseDown(object sender , MouseEventArgs e)//用来进行左右标尺的显示
        {
            Panel pnl= sender as Panel;
            CheckBox chk=pnl.Tag as CheckBox;

            if (int.TryParse(ZoneGroupChk[chk][0].Tag.ToString() , out int id))
            {
                if (e.Button == MouseButtons.Left)//设置左边的
                {
                    SetAxisText(chk , true);
                    leftAxisCheckbox = chk;
                    return;
                }
                if (e.Button == MouseButtons.Right)//设置右边的
                {
                    rightAxisCheckbox = chk;
                    SetAxisText(chk , false);
                    return;
                }
            }
        }
        private void SetAxisText(CheckBox chk , bool isLeftAxis)
        {
            try
            {
                Zone z = chk.Tag as Zone;
                int.TryParse(ZoneGroupChk[chk][0].Tag.ToString() , out int id);
                Label [] lbl;
                Label lblAxisTitle;
                if (isLeftAxis) { lbl = lbl_AxisLeft; lblAxisTitle = lbl_LeftTitle; }
                else { lbl = lbl_AxisRight; lblAxisTitle = lbl_RightTitle; }
                lblAxisTitle.Text = z.Unit;
                lbl[0].Text = Math.Round(LineSetting[id].AxisMax , 2).ToString();
                lbl[5].Text = Math.Round(LineSetting[id].AxisMin , 2).ToString();
                for (int i = 1 ; i < 5 ; i++)
                {
                    lbl[i].Text = Math.Round((LineSetting[id].AxisMax - LineSetting[id].AxisMin) / 5 * (5 - i) , 2).ToString();
                }
            }
            catch (Exception)
            {
            }

        }
        private void ZonePanel_DoubleClick(object sender , EventArgs e)//用来设置标尺范围
        {
            Panel pnl= sender as Panel;
            CheckBox chk=pnl.Tag as CheckBox;
            if (int.TryParse(ZoneGroupChk[chk][0].Tag.ToString() , out int id))
            {
                Pnl_LimitSet.Tag = chk;
                lbl_LimitSetTitle.Text = chk.Text;
                txt_LimitMax.Text = LineSetting[id].AxisMax.ToString();
                txt_LimitMin.Text = LineSetting[id].AxisMin.ToString();
                Pnl_LimitSet.Visible = true;
            }
        }

        private void Btn_Click(object sender , EventArgs e)
        {
            selectedGroupButton = sender as Button;
            if (int.TryParse(selectedGroupButton.Tag.ToString() , out int groupid))
            {
                ShowZoneSelections(groupid);
            }
        }
        private void EquipChk_CheckedChanged(object sender , EventArgs e)
        {
            CheckBox chk=sender as CheckBox;
            int.TryParse(chk.Tag.ToString() , out int zoneid);
            if (zoneid != 0)
                SetZoneCurveSelection(zoneid , chk.Checked);
            showCurveByDay();
        }
        private void SetZoneCurveSelection(int zoneid , bool value)
        {
            inifile.Write("Zone" + zoneid , "isshow" , value ? "1" : "0");
        }
        private bool GetZoneCurveSelection(int zoneid)
        {
            bool isshow=true;
            if (int.TryParse(inifile.ReadValue("Zone" + zoneid , "isshow") , out int c))
                isshow = c == 1 ? true : false;
            return isshow;
        }
        private Label CreateLabel(Point pt , Color bgColor , object tag)
        {
            Label lbl=new Label()
            {
                Size = new Size(16 , 16) ,
                Location = pt ,
                Tag = tag ,
                BorderStyle=BorderStyle.FixedSingle,
                BackColor = bgColor
            };
            lbl.Click += ColorLbl_Click;
            return lbl;
        }
        private void ColorLbl_Click(object sender , EventArgs e)
        {
            Label lbl =sender as Label;
            int.TryParse(lbl.Tag.ToString() , out int itemid);
            if (itemid != 0)
            {
                ColorDialog cd=new ColorDialog();
                cd.Color = lbl.BackColor;
                DialogResult res=cd.ShowDialog();
                if (res == DialogResult.OK)
                {
                    lbl.BackColor = cd.Color;
                    LineSetting[itemid].CurveColor = lbl.BackColor;
                    LineSetting[itemid].SaveCurveSetting();
                    showCurveByDay();
                }
            }
        }
        private CheckBox CreateCheckBox(string txt , Size sz , Point pt , object tag , bool value)
        {
            CheckBox chk=new CheckBox()
            {
                Text = txt,
                Size = sz ,
                Location = pt,
                Checked=value,
                Tag = tag
            };
            chk.CheckedChanged += ItemChk_CheckedChanged;
            return chk;
        }
        private void ItemChk_CheckedChanged(object sender , EventArgs e)
        {
            CheckBox chk=sender as CheckBox;
            int.TryParse(chk.Tag.ToString() , out int itemid);
            if (itemid != 0)
            {
                LineSetting[itemid].isshow = chk.Checked;
                LineSetting[itemid].SaveCurveSetting();
                showCurveByDay();
            }
        }


        private void showCurveByDay()
        {
            pic_Curve.Image = null;
            RemoveEquipLabels();
            Xscale = 1;
            hScroll.Visible = queryMinutes > visiableminutes;
            if (hScroll.Visible)
            {
                hScroll.Minimum = 0;
                hScroll.Maximum = (queryMinutes - visiableminutes) / 15 + 1;
            }
            Bitmap  bm = new Bitmap(pic_Curve.Width  , pic_Curve.Height);
            DrawBgGrid(bm);
            foreach (CheckBox chk in ZoneGroupChk.Keys)
            {
                if (chk.Checked)
                {
                    foreach (CheckBox itemchk in ZoneGroupChk[chk])
                    {
                        if (itemchk.Checked)
                        {
                            if (int.TryParse(itemchk.Tag.ToString() , out int itemid))
                            {
                                DrawOneCurve(bm , itemid);
                            }
                        }
                    }
                }
            }
            pic_Curve.Image = bm;
            LoadDayCurveInfoControls();
        }
        private void LoadDayCurveInfoControls()
        {
            TimeLine.Height = pic_Curve.Height - 31;
            TimeLabel.Text = StartTime.ToString("yyyy-MM-dd HH:mm");

            pic_Curve.Controls.Add(TimeLine);
            pic_Curve.Controls.Add(TimeData);
            pic_Curve.Controls.Add(TimeLabel);
            TimeLabel.Top = pic_Curve.Height - 32 - TimeLabel.Height;
        }
        private void DrawBgGrid(Bitmap bm)
        {
            if (bm.Width == 0 || bm.Height == 0) return;
            int h = bm.Height - YAxisHeight;
            int w=bm.Width;
            //画横向的线

            int smallDiv = h  / 50;
            int bigDiv = smallDiv*10;
            h = bigDiv * 5;
            CurveHeight = h;
            Graphics g = Graphics.FromImage(bm);
            Pen p = new Pen(Color.Gray, 1);

            for (int i = 0 ; i < 5 ; i++)
            {
                p.Color = Color.DarkGray;
                g.DrawLine(p , 0 , i * bigDiv , w , i * bigDiv);
                lbl_AxisRight[i].Top = lbl_AxisLeft[i].Top = i * bigDiv - 5;
                lbl_AxisRight[i].Text = Math.Round(limit[1 , 2] - limit[1 , 2] / 5 * i , 2).ToString();
                lbl_AxisLeft[i].Text = Math.Round(limit[1 , 0] - limit[1 , 0] / 5 * i , 2).ToString();
                p.Color = Color.LightGray;
                for (int j = 1 ; j < 10 ; j++)
                {
                    g.DrawLine(p , 0 , i * bigDiv + j * smallDiv , w , i * bigDiv + j * smallDiv);
                }
            }
            p.Color = Color.DarkGray;
            g.DrawLine(p , 0 , h , w , h);
            lbl_AxisRight[0].Top = lbl_AxisLeft[0].Top = 0;
            lbl_AxisRight[5].Top = lbl_AxisLeft[5].Top = h - 8;
            lbl_AxisRight[5].Text = lbl_AxisLeft[5].Text = "0";
            //画纵向的线
            SolidBrush brush = new SolidBrush(Color.Black);
            int xIndex = 0;
            int min=0;
            SizeF sf;
            StringBuilder sb;
            while (xIndex * 120 < w)
            {
                p.Color = Color.DarkGray;
                g.DrawLine(p , xIndex * 120 , 0 , xIndex * 120 , h);
                min = (xIndex * 120) / Xscale;
                //sb = new StringBuilder(xIndex.ToString("00") + ":00");
                sb = new StringBuilder().Append((min / 60).ToString("00")).Append(":").Append((min % 60).ToString("00"));
                sf = fdPublicFunction.GetTextSize(this.Font , sb);
                g.DrawString(sb.ToString() , this.Font , brush , new PointF(xIndex * 120f - sf.Width / 2 , h + 2));
                xIndex++;
            }
            g.DrawLine(p , w - 1 , 0 , w - 1 , h);
            g.DrawString(StartTime.ToString("yyyy-MM-dd HH:mm:00") , this.Font , brush , new PointF(0 , h + 14));
            string s=StartTime.AddMinutes(bm.Width/Xscale).ToString("yyyy-MM-dd HH:mm:00");
            g.DrawString(s , this.Font , brush , new PointF(bm.Width - g.MeasureString(s , this.Font).Width + 2 , h + 14));
        }
        private void DrawOneCurve(Bitmap bm , int ItemIndex)
        {
            Pen p=new Pen(LineSetting[ItemIndex].CurveColor,2);
            Graphics g = Graphics.FromImage(bm);
            float x0, y0, x1, y1;
            x0 = 0;
            y0 = CurveHeight * (LineSetting[ItemIndex].AxisMax - LineData[ItemIndex][0]) / (LineSetting[ItemIndex].AxisMax - LineSetting[ItemIndex].AxisMin);
            for (int j = 1 ; j < LineData[ItemIndex].Length ; j++)
            {
                y1 = CurveHeight * (LineSetting[ItemIndex].AxisMax - LineData[ItemIndex][j]) / (LineSetting[ItemIndex].AxisMax - LineSetting[ItemIndex].AxisMin);
                x1 = j * Xscale;
                if (LineData[ItemIndex][j] * LineData[ItemIndex][j - 1] != 0)
                {
                    g.DrawLine(p , x0 , y0 , x1 , y1);
                }
                y0 = y1;
                x0 = x1;
            }
        }
        private void RemoveEquipLabels()
        {
            pic_Curve.Controls.Clear();
            if (Equiplbl.Count > 0)
            {
                foreach (Label item in Equiplbl)
                    item.Dispose();
            }
            Equiplbl.Clear();
        }
        private void LoadDayCurveSetting()
        {//显示天数据时的设置

            foreach (int i in QueryForms.fmquery.netline.zone.Keys)
            {
                if (QueryForms.fmquery.netline.zone[i].isShowCurve)
                {
                    if (QueryForms.fmquery.netline.zone[i].pv != null)
                    {
                        LineSetting.Add(QueryForms.fmquery.netline.zone[i].pv.ID , new CurveSetting(QueryForms.fmquery.netline.zone[i].pv.ID));
                        LineData.Add(QueryForms.fmquery.netline.zone[i].pv.ID , new float[pic_Curve.Width]);
                        pvmaxmin.Add(QueryForms.fmquery.netline.zone[i].pv.ID , new PVMaxMin() { zonename= QueryForms.fmquery.netline.zone[i].ZoneName});
                    }
                    if (QueryForms.fmquery.netline.zone[i].sv != null)
                    {
                        LineSetting.Add(QueryForms.fmquery.netline.zone[i].sv.ID , new CurveSetting(QueryForms.fmquery.netline.zone[i].sv.ID));
                        LineData.Add(QueryForms.fmquery.netline.zone[i].sv.ID , new float[pic_Curve.Width]);
                    }
                    if (QueryForms.fmquery.netline.zone[i].ovpv != null)
                    {
                        LineSetting.Add(QueryForms.fmquery.netline.zone[i].ovpv.ID , new CurveSetting(QueryForms.fmquery.netline.zone[i].ovpv.ID));
                        LineData.Add(QueryForms.fmquery.netline.zone[i].ovpv.ID , new float[pic_Curve.Width]);
                    }
                }
            }

        }

        private void GetDayData(DateTime SearchDay)
        {
            int totalminutes=pic_Curve.Width;
            if (totalminutes < 1440) totalminutes = 1440;
            DataTable dt =DBOperate.GetParameterData(SearchDay.Date,SearchDay.Date.AddMinutes(totalminutes));
            StartTime = SearchDay.Date;
            DateTime edTime;
            foreach (int itemid in LineData.Keys)
            {
                Array.Clear(LineData[itemid] , 0 , LineData[itemid].Length);
                //LineData[itemid] = new float[totalminutes];
                bool isHaveID = pvmaxmin.ContainsKey(itemid);
                if (isHaveID) { pvmaxmin[itemid].min = 9999f; pvmaxmin[itemid].max = 0; }
                if (dt == null || dt.Rows.Count == 0) continue;
                for (int i = 0 ; i < dt.Rows.Count ; i++)
                {
                    try
                    {
                        edTime = Convert.ToDateTime(dt.Rows[i]["savetime"]);
                        int minuteinterval = (int)edTime.Subtract(StartTime).TotalMinutes;
                        LineData[itemid][minuteinterval] = Convert.ToSingle(dt.Rows[i][itemid.ToString()]);
                        if (isHaveID)//进行数据的统计
                        {
                            if(pvmaxmin[itemid].max< LineData[itemid][minuteinterval])
                            {
                                pvmaxmin[itemid].max = LineData[itemid][minuteinterval];
                                pvmaxmin[itemid].maxtime = edTime;
                            }
                            if(pvmaxmin[itemid].min> LineData[itemid][minuteinterval] && LineData[itemid][minuteinterval] != 0)
                            {
                                pvmaxmin[itemid].min = LineData[itemid][minuteinterval];
                                pvmaxmin[itemid].mintime = edTime;
                            }
                        }
                        Application.DoEvents();
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
        }

        private void pic_Curve_MouseMove(object sender , MouseEventArgs e)
        {
            if (gp_LoadData.Visible) return;
            TimeLabel.Visible = TimeLine.Visible = TimeData.Visible = true;
            TimeLine.Left = e.X;
            TimeLabel.Text = StartTime.AddMinutes(e.X).ToString("yyyy-MM-dd HH:mm");
            StringBuilder sb=new StringBuilder();
            if (e.X < queryMinutes)
            {
                foreach (CheckBox zonechk in ZoneGroupChk.Keys)
                {
                    sb.Append(zonechk.Text).Append(":");
                    foreach (CheckBox chk in ZoneGroupChk[zonechk])
                    {
                        int.TryParse(chk.Tag.ToString() , out int v);
                        sb.Append(chk.Text).Append(":").Append(LineData[v][e.X]).Append(" ");
                    }
                    sb.Append("\n");
                }
            }
            TimeData.Text = sb.ToString();
            if (e.X > pic_Curve.Width / 2)
            {
                TimeData.Left = e.X - 2 - TimeData.Width;
                TimeLabel.Left = e.X - 2 - TimeLabel.Width;
            }
            else
            {
                TimeLabel.Left = TimeData.Left = e.X + 2;
            }
        }

        private void pic_Curve_MouseLeave(object sender , EventArgs e)
        {
            TimeData.Visible = TimeLine.Visible = false;
        }

        private void btn_Query_Click(object sender , EventArgs e)
        {
            QueryOneDayData(dtp_Day.Value);
        }

        private void QueryOneDayData(DateTime _queryDate)
        {
            if (lastQueryDate != _queryDate)
            {
                gp_LoadData.Visible = true;
                lastQueryDate = _queryDate;
                Application.DoEvents();
                GetDayData(_queryDate);
                showCurveByDay();
                gp_LoadData.Visible = false;

            }
        }

        private void dtp_Day_KeyPress(object sender , KeyPressEventArgs e)
        {
            if(e.KeyChar==(char)Keys.Enter)
                QueryOneDayData(dtp_Day.Value);

        }

        private void btn_DateAnalyze_Click(object sender , EventArgs e)
        {
            Form_DayMaxMin fmmaxmin=new Form_DayMaxMin(pvmaxmin);
            fmmaxmin.ShowDialog();

        }

        private void btn_ShowAlarm_Click(object sender , EventArgs e)
        {
            Form_QueryAlarmByDay fmalarm=new Form_QueryAlarmByDay( true ,"", dtp_Day.Value, dtp_Day.Value.Date.AddDays(1).AddSeconds(-1));
            fmalarm.ShowDialog();
        }

        private void btn_LimitConfirm_Click(object sender , EventArgs e)
        {
            if (float.TryParse(txt_LimitMin.Text , out float min) && float.TryParse(txt_LimitMax.Text , out float max))
            {
                if (max == min)
                {
                    MessageBox.Show("输入的上下值不能相同。" , "限值设置");
                    return;
                }
                CheckBox chk = Pnl_LimitSet.Tag as CheckBox;
                for (int i = 0 ; i < ZoneGroupChk[chk].Count ; i++)
                {
                    CheckBox zonechk = ZoneGroupChk[chk][i] as CheckBox;
                    if (int.TryParse(zonechk.Tag.ToString() , out int id))
                    {
                        LineSetting[id].AxisMax = max > min ? max : min;
                        LineSetting[id].AxisMin = max > min ? min : max;
                        Pnl_LimitSet.Visible = false;
                        LineSetting[id].SaveCurveSetting();
                    }
                }
                showCurveByDay();
            }
            else
            {
                MessageBox.Show("请正确的输入上下限数值。" , "限值设置");
            }
        }

        private void btn_LimitCancel_Click(object sender , EventArgs e)
        {
            Pnl_LimitSet.Visible = false;
        }

        private void hScroll_Scroll(object sender , ScrollEventArgs e)
        {
            pic_Curve.Left = -hScroll.Value * 15 + pic_AxisL.Width;
        }
    }
    public class CurveSetting
    {
        public float AxisMin { get; set; } = 0;
        public float AxisMax { get; set; } = 1000;
        public Color CurveColor { get; set; } = Color.Black;

        public bool isshow=true;

        private string _sectionID="";

        private Ini Curveset=new Ini(Application.StartupPath+"\\settings\\Curve.dat");

        public CurveSetting(int sectionid)
        {
            _sectionID = sectionid.ToString();
            float v;
            int c;
            if (float.TryParse(Curveset.ReadValue(_sectionID , "AxisMin") , out v))
                AxisMin = v;
            if (float.TryParse(Curveset.ReadValue(_sectionID , "AxisMax") , out v))
                AxisMax = v;
            if (int.TryParse(Curveset.ReadValue(_sectionID , "CurveColor") , out c))
                CurveColor = Color.FromArgb(c);
            if (int.TryParse(Curveset.ReadValue(_sectionID , "isshow") , out c))
                isshow = c == 0 ? false : true;
        }

        public void SaveCurveSetting()
        {
            if (_sectionID == "") return;
            Curveset.Write(_sectionID , "AxisMin" , AxisMin.ToString());
            Curveset.Write(_sectionID , "AxisMax" , AxisMax.ToString());
            Curveset.Write(_sectionID , "CurveColor" , CurveColor.ToArgb().ToString());
            Curveset.Write(_sectionID , "isshow" , isshow ? "1" : "0");
        }
    }

    public class PVMaxMin
    {
       
        public string zonename { get; set; }
        public int id { get; set; }
        public float max { get; set; } = 0;
        public float min { get; set; } = 9999f;
        public DateTime maxtime { get; set; }
        public DateTime mintime { get; set; }
    }
}
